package com.company.genealogy.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.company.genealogy.common.result.ApiResponse;
import com.company.genealogy.web.dto.BranchDTO;
import com.company.genealogy.web.entity.Branch;
import com.company.genealogy.web.service.BranchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.company.genealogy.common.constant.ApiCodeEnum;

import java.util.List;

@RestController
@RequestMapping("/api/v1/branches")
public class BranchController {
    @Autowired
    private BranchService branchService;

    // 分页查询分支列表（包含家族名称和负责人名称）
    @GetMapping
    public ApiResponse<IPage<BranchDTO>> list(@RequestParam(defaultValue = "1") int page,
                                           @RequestParam(defaultValue = "10") int size,
                                           @RequestParam(required = false) Long clanId) {
        IPage<BranchDTO> result = branchService.getBranchListWithNames(page, size, clanId);
        return ApiResponse.success(ApiCodeEnum.SUCCESS, result);
    }

    // 根据家族ID获取分支列表
    @GetMapping("/clan/{clanId}")
    public ApiResponse<List<Branch>> getBranchesByClanId(@PathVariable Long clanId) {
        List<Branch> branches = branchService.getBranchesByClanId(clanId);
        return ApiResponse.success(ApiCodeEnum.SUCCESS, branches);
    }

    // 新增分支
    @PostMapping
    public ApiResponse<Branch> create(@RequestBody Branch branch) {
        branchService.save(branch);
        return ApiResponse.success(ApiCodeEnum.SUCCESS, branch);
    }

    // 分支详情
    @GetMapping("/{id}")
    public ApiResponse<Branch> detail(@PathVariable Long id) {
        Branch branch = branchService.getById(id);
        return ApiResponse.success(ApiCodeEnum.SUCCESS, branch);
    }

    // 编辑分支
    @PutMapping("/{id}")
    public ApiResponse<Void> update(@PathVariable Long id, @RequestBody Branch branch) {
        branch.setId(id);
        branchService.updateById(branch);
        return ApiResponse.success(ApiCodeEnum.SUCCESS, null);
    }

    // 删除分支
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        branchService.removeById(id);
        return ApiResponse.success(ApiCodeEnum.SUCCESS, null);
    }
} 